<template>
  <el-dialog v-model="dialogVisible" class="center" title="新增二级分类" width="400px" draggable>
    <el-form ref="ruleFormRef" :model="dialogProps.row" :rules="rules" label-width="100px">
      <el-form-item label="一级分类选择">
        <el-select v-model="dialogProps.row!.listId" clearable>
          <el-option v-for="option in result" :key="option.listId" :label="option.listName" :value="option.listId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类名称" prop="setName" v-if="isFirstLevelSelected">
        <el-input v-model="dialogProps.row!.setName" clearable></el-input>
      </el-form-item>
      <el-form-item label="二级分类描述" prop="setDescription" v-if="isFirstLevelSelected">
        <el-input v-model="dialogProps.row!.setDescription" clearable></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { watch, ref, reactive } from "vue";
import { Good } from "@/api/interface";
import { FormInstance, ElMessage } from "element-plus";
import { addGoodsSet, getGoodsList } from "@/api/modules/good";

const rules = reactive({});

// 提交数据（更改）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    if (!isFirstLevelSelected.value) {
      ElMessage.warning({ message: "请先选择一级分类" });
      return;
    }
    try {
      await addGoodsSet({
        listId: dialogProps.value.row.listId,
        setName: dialogProps.value.row.setName,
        setDescription: dialogProps.value.row.setDescription
      });
      ElMessage.success({ message: `添加二级分类成功` });
      dialogVisible.value = false;
      dialogProps.value.getTableList!();
    } catch (error) {
      console.log(error);
    }
  });
};

interface DialogProps {
  title: string;
  isView: boolean;
  row: Partial<Good.GoodsSet>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const dialogVisible = ref(false);
const dialogProps = ref<DialogProps>({
  isView: false,
  title: "",
  row: {}
});

const isFirstLevelSelected = ref(dialogProps.value.row.listId !== undefined);
watch(
  () => dialogProps.value.row.listId,
  () => {
    isFirstLevelSelected.value = dialogProps.value.row.listId !== undefined;
  }
);

const result = ref<Good.ReqGoodsList[]>();

const openDialog = async (params: DialogProps) => {
  dialogProps.value = params;
  dialogVisible.value = true;
  result.value = (await getGoodsList()).data;
};

defineExpose({ openDialog });
</script>
